package com.fone.player.storage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build.VERSION;

import com.fone.player.entity.OfflineCache;
import com.fone.player.entity.OfflineCacheFragment;
import com.fone.player.storage.download.SaveCacheDataUtil;
import com.fone.player.util.L;

/**
 * 
 * 缓存表适配器
 * 
 * @author wangyang
 * @since 2014年4月29日
 */
public class OfflineCacheFragmentDataBaseAdapter implements IFoneDatabase {
	private static final String TAG = OfflineCacheFragmentDataBaseAdapter.class
			.getSimpleName();
	private static final OfflineCacheFragmentDataBaseAdapter mInstance = new OfflineCacheFragmentDataBaseAdapter();
	private OperateDataBaseTemplate mGeneralDataBaseTemplate = OperateDataBaseTemplate
			.getInstance();

	private OfflineCacheFragmentDataBaseAdapter() {

	}

	public static OfflineCacheFragmentDataBaseAdapter getInstance() {
		return mInstance;
	}

	/**
	 * 
	 * 添加分片列表
	 * 
	 * @param offlineCacheFragmentList
	 *            分片列表
	 * @return void
	 */
	public int addOfflineCacheFragmentList(
			List<OfflineCacheFragment> waitOfflineCacheFragmentList) {
		int count = 0;
		try {
			mGeneralDataBaseTemplate.open();
			// List<OfflineCacheFragment> offlineCacheFragmentList = new
			// ArrayList<OfflineCacheFragment>();
			// for (OfflineCacheFragment offlineCacheFragment :
			// waitOfflineCacheFragmentList) {
			// if (offlineCacheFragment.getCacheFragmentUrl().equals("")) {
			// continue;
			// }
			//
			// String sql = "select * from  " + TB_OFFLINE_CACHE_FRAGMENT
			// + " where " + OFFLINE_CACHE_FRAGMENT_URL + "='"
			// + offlineCacheFragment.getCacheFragmentUrl() + "'";
			// Cursor cursor = mGeneralDataBaseTemplate.select(sql);
			// if (cursor != null && cursor.getCount() > 0) {
			// // 重复
			// } else {
			// offlineCacheFragmentList.add(offlineCacheFragment);
			// }
			// cursor.close();
			// }

			mGeneralDataBaseTemplate.beginTransaction();
			for (OfflineCacheFragment offlineCacheFragment : waitOfflineCacheFragmentList) {

				ContentValues contentValues = new ContentValues();
				contentValues.put(OFFLINE_CACHE_FRAGMENT_CID,
						offlineCacheFragment.getCacheCID());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_INDEX,
						offlineCacheFragment.getCacheCurrentIndex());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_DOWNLOAD_STATE,
						offlineCacheFragment.getCacheDownloadState());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_URL,
						offlineCacheFragment.getCacheFragmentUrl());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_URL_MD5,
						offlineCacheFragment.getCacheFragmentUrlMD5());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_ALREADY_SIZE,
						offlineCacheFragment.getCacheAlreadySize());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_TOTAL_SIZE,
						offlineCacheFragment.getCacheTotalSize());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_DURATION,
						offlineCacheFragment.getCacheDuration());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_DEFINITION_TYPE,
						offlineCacheFragment.getCacheDefinitionType());
				// 重复的文件夹做忽略处理
				if (VERSION.SDK_INT < 8) {
					try {
						mGeneralDataBaseTemplate.insertOrThrow(
								TB_OFFLINE_CACHE_FRAGMENT, null, contentValues);
					} catch (Exception e) {
						if (e != null) {
							L.e(TAG,
									"addOfflineCacheFragmentList",
									"md5="
											+ offlineCacheFragment
													.getCacheFragmentUrlMD5()
											+ " downloadUrl="
											+ offlineCacheFragment
													.getCacheFragmentUrl());
							e.printStackTrace();
						}
					}

				} else {

					mGeneralDataBaseTemplate.insertWithOnConflict(
							TB_OFFLINE_CACHE_FRAGMENT, null, contentValues,
							SQLiteDatabase.CONFLICT_IGNORE);
				}

			}
			count = 1;
		} catch (Exception e) {
			if (e != null) {
				e.printStackTrace();
			}
		} finally {
			mGeneralDataBaseTemplate.setTransactionSuccessful();
			mGeneralDataBaseTemplate.endTransaction();
		}
		return count;
	}

	/**
	 * 
	 * 添加分片列表
	 * 
	 * @param offlineCacheFragmentList
	 *            分片列表
	 * @return void
	 */
	public int addOfflineCacheFragmentList(SQLiteDatabase sqliteDatabase,
			List<OfflineCacheFragment> waitOfflineCacheFragmentList) {
		int count = 0;
		try {
			// List<OfflineCacheFragment> offlineCacheFragmentList = new
			// ArrayList<OfflineCacheFragment>();
			// for (OfflineCacheFragment offlineCacheFragment :
			// waitOfflineCacheFragmentList) {
			// if (offlineCacheFragment.getCacheFragmentUrl().equals("")) {
			// continue;
			// }
			//
			// String sql = "select * from  " + TB_OFFLINE_CACHE_FRAGMENT
			// + " where " + OFFLINE_CACHE_FRAGMENT_URL + "='"
			// + offlineCacheFragment.getCacheFragmentUrl() + "'";
			// Cursor cursor = sqliteDatabase.rawQuery(sql, null);
			// if (cursor != null && cursor.getCount() > 0) {
			// // 重复
			// } else {
			// offlineCacheFragmentList.add(offlineCacheFragment);
			// }
			// cursor.close();
			// }

			sqliteDatabase.beginTransaction();
			for (OfflineCacheFragment offlineCacheFragment : waitOfflineCacheFragmentList) {

				ContentValues contentValues = new ContentValues();
				contentValues.put(OFFLINE_CACHE_FRAGMENT_CID,
						offlineCacheFragment.getCacheCID());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_INDEX,
						offlineCacheFragment.getCacheCurrentIndex());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_DOWNLOAD_STATE,
						offlineCacheFragment.getCacheDownloadState());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_URL,
						offlineCacheFragment.getCacheFragmentUrl());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_URL_MD5,
						offlineCacheFragment.getCacheFragmentUrlMD5());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_ALREADY_SIZE,
						offlineCacheFragment.getCacheAlreadySize());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_TOTAL_SIZE,
						offlineCacheFragment.getCacheTotalSize());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_DURATION,
						offlineCacheFragment.getCacheDuration());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_DEFINITION_TYPE,
						offlineCacheFragment.getCacheDefinitionType());
				// 重复的文件夹做忽略处理
				if (VERSION.SDK_INT < 8) {
					try {
						sqliteDatabase.insertOrThrow(TB_OFFLINE_CACHE_FRAGMENT,
								null, contentValues);
					} catch (Exception e) {
						if (e != null) {
							L.e(TAG,
									"addOfflineCacheFragmentList",
									"md5="
											+ offlineCacheFragment
													.getCacheFragmentUrlMD5()
											+ " downloadUrl="
											+ offlineCacheFragment
													.getCacheFragmentUrl());
							e.printStackTrace();
						}
					}

				} else {

					sqliteDatabase.insertWithOnConflict(
							TB_OFFLINE_CACHE_FRAGMENT, null, contentValues,
							SQLiteDatabase.CONFLICT_IGNORE);
				}

			}
			count = 1;
		} catch (Exception e) {
			if (e != null) {
				e.printStackTrace();
			}
		} finally {
			sqliteDatabase.setTransactionSuccessful();
			sqliteDatabase.endTransaction();
		}
		return count;
	}

	/**
	 * 
	 * 根据缓存CID获取缓存对象分片集合
	 * 
	 * @return List<OfflineCacheFragment> 缓存对象分片集合
	 */
	public List<OfflineCacheFragment> getOfflineCacheFragmentListByCID(long cid) {
		L.v(TAG, "getOfflineCacheFragmentListByCID", "start cid=" + cid);
		OfflineCache offlineCacheFile = OfflineCacheFileDataBaseAdapter
				.getInstance().getOfflineCacheFileByCID(cid);
		List<OfflineCacheFragment> offlineCacheFragmentListTemp = null;
		List<OfflineCacheFragment> offlineCacheFragmentList = new ArrayList<OfflineCacheFragment>();
		if (offlineCacheFile != null) {
			offlineCacheFragmentListTemp = SaveCacheDataUtil.getInstance()
					.getOfflineCacheFragmentListByFilePath(
							offlineCacheFile.getCacheStoragePath());
			if (offlineCacheFragmentListTemp != null) {
				for (OfflineCacheFragment offlineCacheFragment : offlineCacheFragmentListTemp) {
					switch (offlineCacheFragment.getCacheDownloadState()) {
					case OfflineCache.CACHE_STATE_FINISH:
						offlineCacheFragmentList.add(offlineCacheFragment);
						break;
					default:
						// 未完成的过滤
						break;
					}
				}
			}

		}
		return offlineCacheFragmentList;
	}

	/**
	 * 
	 * 根据缓存json路径获取缓存对象分片集合
	 * 
	 * @return List<OfflineCacheFragment> 缓存对象分片集合
	 */
	public List<OfflineCacheFragment> getOfflineCacheFragmentListPlayableByPath(
			String folderPath) {
		L.v(TAG, "getOfflineCacheFragmentListPlayableByPath",
				"start folderPath=" + folderPath);
		List<OfflineCacheFragment> offlineCacheFragmentList = SaveCacheDataUtil
				.getInstance()
				.getOfflineCacheFragmentListByFilePath(folderPath);
		return offlineCacheFragmentList;
	}

	/**
	 * 
	 * 根据缓存文件Id列表删除所有相关的缓存分片 <br>
	 * 同步方法
	 * 
	 * @param offlineCacheFileList
	 *            缓存列表
	 * @return int 操作结果<br>
	 *         1 删除成功<br>
	 *         -1 删除异常<br>
	 */
	public int deleteOfflineCacheFragmentByCID(
			List<OfflineCache> offlineCacheFileList) {
		int result = 1;
		try {

			mGeneralDataBaseTemplate.open();
			mGeneralDataBaseTemplate.beginTransaction();
			for (OfflineCache offlineCacheFile : offlineCacheFileList) {
				StringBuilder where = new StringBuilder();
				where.append(OFFLINE_CACHE_FRAGMENT_CID).append("=?");

				mGeneralDataBaseTemplate.delete(TB_OFFLINE_CACHE_FRAGMENT,
						where.toString(), new String[] { String
								.valueOf(offlineCacheFile.getCacheCID()) });
			}
			mGeneralDataBaseTemplate.setTransactionSuccessful();
		} catch (Exception e) {
			result = -1;
		} finally {

			mGeneralDataBaseTemplate.endTransaction();
			mGeneralDataBaseTemplate.close();
		}
		return result;
	}

	public int updateOfflineCacheFragmentList(
			List<OfflineCacheFragment> offlineCacheFragmentList) {
		L.v(TAG, "updateOfflineCacheFragmentList", "start");
		int count = 0;
		try {

			String where = OFFLINE_CACHE_FRAGMENT_INDEX + " = ? and "
					+ OFFLINE_CACHE_FRAGMENT_CID + "=? and "
					+ OFFLINE_CACHE_FRAGMENT_DEFINITION_TYPE + "=?";
			mGeneralDataBaseTemplate.open();
			mGeneralDataBaseTemplate.beginTransaction();
			for (OfflineCacheFragment offlineCacheFragment : offlineCacheFragmentList) {
				String[] whereValue = {
						String.valueOf(offlineCacheFragment
								.getCacheCurrentIndex()),
						String.valueOf(offlineCacheFragment.getCacheCID()),
						String.valueOf(offlineCacheFragment
								.getCacheDefinitionType()) };
				ContentValues contentValues = new ContentValues();
				contentValues.put(OFFLINE_CACHE_FRAGMENT_DOWNLOAD_STATE,
						offlineCacheFragment.getCacheDownloadState());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_URL,
						offlineCacheFragment.getCacheFragmentUrl());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_URL_MD5,
						offlineCacheFragment.getCacheFragmentUrlMD5());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_ALREADY_SIZE,
						offlineCacheFragment.getCacheAlreadySize());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_TOTAL_SIZE,
						offlineCacheFragment.getCacheTotalSize());
				contentValues.put(OFFLINE_CACHE_FRAGMENT_DURATION,
						offlineCacheFragment.getCacheDuration());
				count = mGeneralDataBaseTemplate.update(
						TB_OFFLINE_CACHE_FRAGMENT, contentValues, where,
						whereValue);
				count = 1;
			}
		} catch (Exception e) {
			if (e != null) {
				e.printStackTrace();
			}
		} finally {
			mGeneralDataBaseTemplate.setTransactionSuccessful();
			mGeneralDataBaseTemplate.endTransaction();
		}
		return count;
	}
}
